package com.example.sbeducation.exception;

import com.example.sbeducation.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  /**
   * 处理参数校验异常
   */
  @ExceptionHandler({ MethodArgumentNotValidException.class, BindException.class })
  public Result<String> handleValidException(Exception e) {
    BindingResult bindingResult;
    if (e instanceof MethodArgumentNotValidException) {
      bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
    } else {
      bindingResult = ((BindException) e).getBindingResult();
    }

    StringBuilder sb = new StringBuilder();
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
      sb.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append(", ");
    }
    String msg = sb.toString();
    if (msg.length() > 2) {
      msg = msg.substring(0, msg.length() - 2);
    }

    log.error("参数校验异常: {}", msg);
    return Result.error(400, msg);
  }

  /**
   * 处理业务异常
   */
  @ExceptionHandler(BusinessException.class)
  public Result<String> handleBusinessException(BusinessException e) {
    log.error("业务异常: {}", e.getMessage());
    return Result.error(e.getCode(), e.getMessage());
  }

  /**
   * 处理其他异常
   */
  @ExceptionHandler(Exception.class)
  public Result<String> handleException(Exception e) {
    log.error("系统异常: ", e);
    return Result.error("系统异常，请联系管理员");
  }
}